import {defineStore} from "pinia";
import {reactive, ref, type UnwrapNestedRefs, watch} from "vue";
import { addCollection, getCollections, getCollectionMessages } from '@/apis/api';
import visitorStore from "./visitor";
import type Qa  from "@/models/QA"
import type {Collection} from "@/models/collection";
const collectionStore = defineStore('collection', () => {
    const collections = reactive<Array<Collection>>([]);
    const curCollectionId = ref('');
    const curCollectionMessages = reactive<Array<Qa>>([]);
    const {getVisitorId} = visitorStore();
    const collectTopicMessage = async  (title: string|undefined, topicId:string, collection:Array<Qa> = []) => {
        const messages: Array<Object> = []
        for (const item of collection) {
            messages.push({qa_id: item.qaId, message_id: item.askMessageId}, {qa_id: item.qaId, message_id: item.answerMessageId});
        }
        await addCollection(title ?? '', getVisitorId() ?? '', {
            topic_id: topicId,
            messages: messages
        });
    }
    const loadCollections = async () => {
        collections.splice(0, collections.length);
        const res = await getCollections(getVisitorId());
        for (const item of res['collect_list']) {
            const collection: Collection = {
                collectionId: item['collection_id'],
                title: item['collection_title'],
                messages: [],
            };
            collections.push(collection);
            if (!curCollectionId.value) {
                curCollectionId.value = item['collection_id'];
            }
        }
    }

    watch(curCollectionId, async (id) => {
        if(id) {
            await loadCollectionMessages(id);
        }
    })
    const loadCollectionMessages = async (id: string) => {
        curCollectionMessages.splice(0, curCollectionMessages.length);
        const res = await getCollectionMessages(id);
        for (const message of res['messages']) {
            const qa: Qa = {
                askMessage: message['ask_message'],
                askMessageId: message['ask_message_id'],
                answerMessage: message['answer_message'],
                answerMessageId: message['answer_message_id'],
                qaId: message['topic_qa_id'],
                collectionId: message['collection_id']
            };
            curCollectionMessages.push(qa);
        }
    }
    return {collections, curCollectionId, collectTopicMessage, loadCollections, curCollectionMessages};
})
export default collectionStore;